from django.contrib import admin

from .models import (
    NotebookAttachment,
    NotebookEntry,
    TopicTraining,
    TopicQuestion,
    TopicProgress,
)


class NotebookAttachmentInline(admin.StackedInline):
    model = NotebookAttachment
    extra = 0
    readonly_fields = ("uploaded_at",)


@admin.register(NotebookEntry)
class NotebookEntryAdmin(admin.ModelAdmin):
    list_display = ("title", "student", "status", "updated_at")
    list_filter = ("status", "published_at")
    search_fields = ("title", "student__username", "student__full_name")
    autocomplete_fields = ("student",)
    filter_horizontal = ("related_mistakes",)
    inlines = (NotebookAttachmentInline,)


class TopicQuestionInline(admin.TabularInline):
    model = TopicQuestion
    extra = 1
    fields = (
        "question_number",
        "question_text",
        "question_image",
        "correct_answer",
        "next_question_if_correct",
        "next_question_if_wrong",
    )
    ordering = ("question_number",)


@admin.register(TopicTraining)
class TopicTrainingAdmin(admin.ModelAdmin):
    list_display = ("title", "created_by", "is_active", "question_count", "created_at")
    list_filter = ("is_active", "created_at")
    search_fields = ("title", "description")
    inlines = (TopicQuestionInline,)
    
    def question_count(self, obj):
        return obj.questions.count()
    question_count.short_description = "题目数量"
    
    def save_model(self, request, obj, form, change):
        if not obj.pk:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(TopicQuestion)
class TopicQuestionAdmin(admin.ModelAdmin):
    list_display = (
        "training",
        "question_number",
        "get_question_preview",
        "next_question_if_correct",
        "next_question_if_wrong",
    )
    list_filter = ("training",)
    search_fields = ("question_text", "training__title")
    ordering = ("training", "question_number")
    
    def get_question_preview(self, obj):
        return obj.question_text[:50] + "..." if len(obj.question_text) > 50 else obj.question_text
    get_question_preview.short_description = "题目预览"


@admin.register(TopicProgress)
class TopicProgressAdmin(admin.ModelAdmin):
    list_display = (
        "student",
        "training",
        "current_question",
        "answer_count",
        "is_completed",
        "started_at",
    )
    list_filter = ("is_completed", "training")
    search_fields = ("student__username", "training__title")
    readonly_fields = ("started_at", "completed_at", "answer_history")
    
    def answer_count(self, obj):
        return len(obj.answer_history)
    answer_count.short_description = "答题数"
